package com.wfm.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wfm.eduservice.entity.EduSubject;
import com.wfm.eduservice.entity.excel.SubjectData;
import com.wfm.eduservice.entity.subject.OneSubject;
import com.wfm.eduservice.entity.subject.TwoSubject;
import com.wfm.eduservice.listener.SubjectExcelListener;
import com.wfm.eduservice.mapper.EduSubjectMapper;
import com.wfm.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfm.servicebase.config.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author wfm
 * @since 2021-03-10
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void importSubjectData(MultipartFile file, EduSubjectService subjectService) {
        try {
            //1 获取文件输入流
            InputStream inputStream = file.getInputStream();
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(inputStream,SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch(Exception e) {
            e.printStackTrace();
            throw new GuliException(20002,"添加课程分类失败");
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询出所有一级分类
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id","0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapper);

        //查询出所有二级分类
        QueryWrapper<EduSubject> wrapper2 = new QueryWrapper<>();
        wrapper.ne("parent_id","0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapper2);

        //封装
        List<OneSubject> list = new ArrayList<>();
        for (EduSubject eduSubject1 : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject1,oneSubject);


            for (EduSubject eduSubject2 : twoSubjectList) {
                TwoSubject twoSubject = new TwoSubject();
                BeanUtils.copyProperties(eduSubject2,twoSubject);
                if(eduSubject2.getParentId().equals(eduSubject1.getId())){
                    oneSubject.getChildren().add(twoSubject);
                }
            }
            list.add(oneSubject);

        }
        return list;
    }
}
